<template>
  <div>
    
    <div v-if="!isAuthenticated" class="login-prompt">
      <el-button type="primary" @click="$router.push({ name: 'profile.login' })">立即登录</el-button>
     
      <div class="sub-router-view">
        <router-view/>
      </div>
    </div>
    <div v-else class="user-profile-container">
      <div class="profile-header">
        <div class="user-info">
      
          <el-avatar :size="60" :src="userInfo.avatar || '/default-avatar.png'" />
          <div class="user-detail">
            <h3>{{ userInfo.nickname }}</h3>
            <el-text type="info">@{{ userInfo.userName }}</el-text>
            <el-tag type="primary">{{ roleName }}</el-tag>
            <el-text>{{ userInfo.userSignature || '暂无签名' }}</el-text>
            <el-text type="info">{{ userInfo.email }}</el-text>
          </div>
          <div class="edit-buttons">
          
            <div class="button-row">
              <el-button type="primary" @click="showEditDialog('nickname')">修改昵称</el-button>
              <el-button @click="showEditDialog('signature')">修改签名</el-button>
              <el-button @click="showEditDialog('password')">修改密码</el-button>
              <el-button @click="showAvatarUpload">上传头像</el-button>
            </div>

        
            <div class="button-row">
              <el-button type="success" @click="$router.push({ path: '/', query: { seller: true } })">我的商品</el-button>
              <el-button type="success" @click="handleSellClick">出售商品</el-button>
             
              <el-button type="warning" @click="showRoleDialog">修改角色</el-button>
            </div>

       
            <div class="button-row">
            
              <el-button type="primary" plain @click="$router.push('/orders')">我的订单</el-button>
              <el-button type="info" plain @click="$router.push('/address-management')">地址管理</el-button>
            </div>

          
            <div class="button-row single-button">
              <el-button type="danger" @click="logout">退出登录</el-button>
            </div>
          </div>
        </div>
      </div>
      <div v-if="['seller', 'both'].includes(userInfo.userType)" class="shop-info-container">
      <el-card v-if="shopList.length" class="shop-card">
        <template #header>
          <div class="shop-header">
            <span>我的店铺</span>
          </div>
        </template>
        <div v-for="shop in shopList" :key="shop.shopId" class="shop-item">
          <el-row :gutter="20">
            <el-col :span="4">
              <el-avatar 
                :size="80" 
                :src="`${apiBase}/shop_images/${shop.shop_logo}`" 
                shape="square"
              />
            </el-col>
            <el-col :span="20" @click="handleShopClick(shop.shopId)" class="shop-info-area">
              <h3>{{ shop.shopName }}</h3>
              <el-text type="info">{{ shop.shopDescription }}</el-text>
              <el-button 
                type="text" 
                icon="el-icon-edit" 
                @click.stop="openEditShop(shop)"
                class="edit-button"
              >
                编辑
              </el-button>
            </el-col>
            
            <el-dialog v-model="editShopDialog.visible" title="编辑店铺信息">
              <el-form :model="editShopDialog.form">
                <el-form-item label="编辑类型">
                  <el-select v-model="editShopDialog.form.opcode">
                    <el-option :value="1" label="修改店铺名称" />
                    <el-option :value="2" label="修改店铺描述" />
                    <el-option :value="3" label="修改店铺Logo" />
                  </el-select>
                </el-form-item>
                
                <el-form-item 
                  :label="editShopDialog.form.opcode === 1 
                    ? '新店铺名称' 
                    : '新店铺描述'"
                >
                  <el-input 
                    v-if="editShopDialog.form.opcode === 1"
                    v-model="editShopDialog.form.shopName" 
                  />
                  <el-input 
                    v-else
                    v-model="editShopDialog.form.shopDescription" 
                    type="textarea"
                  />
                </el-form-item>
                
                <el-form-item 
                  v-if="editShopDialog.form.opcode === 3"
                  label="上传新Logo"
                >
                  <input 
                    type="file"
                    accept="image/*"
                    @change="handleShopLogoUpload"
                  >
                </el-form-item>
              </el-form>
              
              <template #footer>
                <el-button @click="editShopDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitShopEdit">提交</el-button>
              </template>
            </el-dialog>
          </el-row>
        </div>
      </el-card>
      
      <div v-else class="create-shop">
        <el-button 
          type="primary" 
          @click="$router.push({ name: 'create-shop' })"
        >
          创建店铺
        </el-button>
      </div>
    </div>
      <!-- 子路由视图容器 -->
      <div class="sub-router-view">
        <router-view/>
      </div>

     
      <el-dialog v-model="editDialog.visible" :title="'修改' + editDialog.type">
        <el-form :model="editDialog.form" label-width="80px">
          <el-form-item label="新昵称" v-if="editDialog.type === 'nickname'">
            <el-input v-model="editDialog.form.nickname" />
          </el-form-item>
          <el-form-item label="新签名" v-if="editDialog.type === 'signature'">
            <el-input v-model="editDialog.form.signature" type="textarea" />
          </el-form-item>
          <el-form-item label="原密码" v-if="editDialog.type === 'password'">
            <el-input v-model="editDialog.form.oldPassword" type="password" show-password />
          </el-form-item>
          <el-form-item label="新密码" v-if="editDialog.type === 'password'">
            <el-input v-model="editDialog.form.newPassword" type="password" show-password />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确认</el-button>
        </template>
      </el-dialog>

      <el-dialog v-model="roleDialogVisible" title="修改用户角色">
        <el-radio-group v-model="selectedRole">
          <el-radio label="buyer">买家</el-radio>
          <el-radio label="seller">卖家</el-radio>
          <el-radio label="both">高级用户</el-radio>
        </el-radio-group>
        <template #footer>
          <el-button @click="roleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateUserType">确认</el-button>
        </template>
      </el-dialog>
      <sell-product-dialog ref="sellDialog" @success="handleSellSuccess" />
    </div>
  </div>
</template>

<script setup>
import { computed, ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getToken, removeToken } from '@/utils/storage';
import axios from 'axios';
import api from '@/api';
import { ElMessage } from 'element-plus';
import SellProductDialog from '@/components/SellProductDialog.vue';


const router = useRouter();
const route = useRoute();
const apiBase = 'http://localhost:8080'; // 硬编码确保接口地址正确

const handleSellClick = () => {
  if (userInfo.value.userType === 'buyer') {
    ElMessage({
      type: 'warning',
      message: '请注册店铺后操作！',
      duration: 3000
    });
    return;
  }
  openSellDialog();
};
const isAuthenticated = computed(() => !!getToken());
const roleMapping = {
  buyer: '买家',
  seller: '卖家',
  both: '高级用户'
};

const userInfo = ref({});
const shopList = ref([]); // 新增店铺信息响应式变量

// 新增获取店铺信息方法
const fetchShopInfo = async () => {
  try {
    const response = await api.get(`${apiBase}/shop/select`);
    shopList.value = response.data;
  } catch (error) {
    console.error('获取店铺信息失败:', error);
  }
};

// 在用户信息获取后触发店铺信息获取
onMounted(() => {
  fetchUserInfo().then(() => {
    if (['seller', 'both'].includes(userInfo.value.userType)) {
      fetchShopInfo();
    }
  });
});
const roleName = computed(() => roleMapping[userInfo.value.userType] || '未知角色');
const editDialog = reactive({
  visible: false,
  type: '',
  form: {}
});

const roleDialogVisible = ref(false);
const selectedRole = ref('');

const showEditDialog = (type) => {
  editDialog.type = type;
  editDialog.form = {
    nickname: userInfo.value.nickname || '',
    signature: userInfo.value.signature,
    oldPassword: '',
    newPassword: ''
  };
  editDialog.visible = true;
};

const confirmEdit = async () => {
  try {
    switch (editDialog.type) {
      case 'nickname':
        await updateNickname();
        break;
      case 'signature':
        await updateSignature();
        break;
      case 'password':
        await updatePassword();
        break;
    }
    editDialog.visible = false;
  } catch (error) {
    console.error('更新失败:', error);
  }
};

const updateNickname = async () => {
  try {
    console.log('尝试更新昵称:', editDialog.form.nickname);
    await api.put(`${apiBase}/user/nickname`, { userNickname: editDialog.form.nickname });
    userInfo.value.nickname = editDialog.form.nickname;
    ElMessage.success('昵称更新成功');
  } catch (error) {
    ElMessage.error('更新失败: ' + error.response?.data?.message || error.message);
    console.error('更新昵称错误:', error);
  }
};

const updateSignature = async () => {
  try {
    await api.put(`${apiBase}/user/signature`, { 
      userSignature: editDialog.form.signature 
    });
    
    // 重新获取最新用户数据
    await fetchUserInfo();
    ElMessage.success('签名更新成功');
  } catch (error) {
    ElMessage.error('更新失败: ' + error.response?.data?.message || error.message);
  }
};

const updatePassword = async () => {
  try {
    console.log('尝试修改密码');
    await api.put(`${apiBase}/user/password`, {
      userPassword1: editDialog.form.oldPassword,
      userPassword2: editDialog.form.newPassword
    });
    removeToken();
    router.push('/login');
    ElMessage.success('密码修改成功，请重新登录');
  } catch (error) {
    ElMessage.error('密码修改失败');
  }
};

const showRoleDialog = () => {
  selectedRole.value = userInfo.value.userType || '';
  roleDialogVisible.value = true;
};

const updateUserType = async () => {
  try {
    await api.put(`${apiBase}/user/${selectedRole.value}`);
    await fetchUserInfo();
    ElMessage.success('角色更新成功');
    roleDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('更新失败: ' + error.response?.data?.message || error.message);
  }
};

const showAvatarUpload = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.onchange = (e) => {
    const file = e.target.files[0];
    if (file) handleAvatarUpload(file);
  };
  input.click();
};

const handleAvatarUpload = async (file) => {
  const formData = new FormData();
  formData.append('userImage', file);
  try {
    const response = await api.put(`${apiBase}/user/image`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    userInfo.value.avatar = URL.createObjectURL(file);
    ElMessage.success('头像更新成功');
  } catch (error) {
    ElMessage.error('头像上传失败');
  }
};

onMounted(() => {
  fetchUserInfo();
});

const fetchUserInfo = async () => {
  try {
    const response = await api.get('/user');
    userInfo.value = {
      userId: response.data.user_id,
      userName: response.data.user_name,
      nickname: response.data.user_nickname || response.data.user_name,
      userType: response.data.user_type,
      userSignature: response.data.user_signature || response.data.signature,
      avatar: response.data.user_image 
        ? `${apiBase}/user_images/${response.data.user_image}`
        : '/default-avatar.png',
      email: response.data.user_email
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败');
    console.error(error);
  }
};

const logout = async () => {
  try {
    // 调用后端注销接口
    await api.post(`${apiBase}/logout`, null, {
      headers: {
        Authorization: `Bearer ${getToken()}`
      }
    });
  } catch (error) {
    console.error('注销请求失败:', error);
    ElMessage.error('注销请求失败，但仍已清除本地凭证');
  } finally {
    // 确保本地凭证清除
    removeToken();
    userInfo.value = {};
    router.push('/profile/login');
    ElMessage.success('已安全退出登录');
    location.reload();
  }
};

const sellDialog = ref();
const openSellDialog = () => {
  sellDialog.value.openDialog();
};
const handleSellSuccess = () => {
  ElMessage.success('商品发布成功！');
};
const editShopDialog = reactive({
  visible: false,
  shopId: null,
  form: {
    opcode: 1,
    shopName: '',
    shopDescription: ''
  }
});

const openEditShop = (shop) => {
  editShopDialog.shopId = shop.shopId;
  editShopDialog.form = {
    opcode: 1,
    shopName: shop.shopName,
    shopDescription: shop.shopDescription
  };
  editShopDialog.visible = true;
};

const submitShopEdit = async () => {
  try {
    const payload = {
      opcode: editShopDialog.form.opcode,
      // 根据opcode动态切换字段名
      ...(editShopDialog.form.opcode === 1 
        ? { shopName: editShopDialog.form.shopName }
        : { shopDescription: editShopDialog.form.shopDescription })
    };
    
    await api.post(`${apiBase}/shop/shopInfo`, payload);
    await fetchShopInfo();
    ElMessage.success('修改成功');
    editShopDialog.visible = false;
  } catch (error) {
    ElMessage.error('修改失败: ' + error.response?.data?.message || error.message);
  }
};
const handleShopClick = (shopId) => {
  if (!shopList.value.length) {
    ElMessage.warning('请先创建店铺');
    return;
  }
  router.push({ 
    name: 'Home',  // 使用路由名称更安全
    query: {
      shopId: shopId
    }
  });
};
const handleShopLogoUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('shopLogo', file);
  formData.append('shopId', editShopDialog.shopId);

  try {
    await api.post(`${apiBase}/shop/shopLogo`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${getToken()}`  // 新增认证头
      }
    });
    await fetchShopInfo();
    ElMessage.success('Logo更新成功');
  } catch (error) {
    ElMessage.error('上传失败: ' + error.response?.data?.message || error.message);
  }
};
</script>

<style scoped>
.edit-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.button-row {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.button-row.single-button {
  justify-content: center;
}


.profile-header {
  padding: 20px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-detail {
  display: flex;
  flex-direction: column;
}
.shop-info-container {
  margin-top: 20px;
  
  .shop-card {
    margin-bottom: 20px;
    
    .shop-header {
      font-size: 16px;
      font-weight: bold;
    }
    
    .shop-item {
      padding: 15px 0;
      border-bottom: 1px solid #eee;
      
      &:last-child {
        border-bottom: none;
      }
    }
  }
  
  .create-shop {
    padding: 20px;
    background: #fff;
    text-align: center;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
}
.sub-router-view {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  min-height: 300px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.edit-button {
  cursor: pointer;
  padding: 10px;
  transition: background-color 0.3s;
  
  &:hover {
    background-color: rgba(64, 158, 255, 0.1);
    border-radius: 4px;
  }
}
</style>

